import React, { useState, lazy, Suspense, useReducer } from 'react'
/* import Home from './pages/Home'
import Sublist from './pages/Sublist'
import My from './pages/My'
import Details from './pages/Details'
import Login from './pages/Login' */
import { Switch, Route, Redirect, withRouter, useHistory, useLocation } from 'react-router-dom'

import { Tabbar } from 'react-vant'
import { FriendsO, HomeO, Search, SettingO } from '@react-vant/icons'

import { reducer, initState } from './store/redcer'//引入管理员函数和管理状态 给useReducer
import Ctx from './store/Ctx'
import { useEffect } from 'react'
/* 
函数组件获取路由信息对象?
1.Route配置后的组件 组件的props中自带路由信息对象
2.没有Route配置后的组件:
  2-1使用withRouter嵌套
  2-2路由库提供hook (useHistory useLocation)

按需加载路由?
 为什么要按需加载路由
 引入的资源 都会在初始加载的时候 被加载出来 导致首页速度加载速慢
 使用到的使用 再被加载出来
*/

//按需加载
let Home = lazy(() => import('./pages/Home'))
let Sublist = lazy(() => { return import('./pages/Sublist') })
let My = lazy(() => import('./pages/My'))
let Details = lazy(() => import('./pages/Details'))
let Login = lazy(() => import('./pages/Login'))

function App(props) {

  /* 
  实现路由守卫
  app是所有路由组件的父级组件
  所有的路由组件都是app的子组件 === div 元素
  home=div sublist = div
  走的都是app组件更新的周期
  */

  //console.log(props);
  //使用路由库提供的hook
  let history = useHistory()
  let location = useLocation()

  useEffect(()=>{
    if(location.pathname!=='/login'){
      let token = localStorage.getItem('token')
      if(!token){
        history.push('login')
      }
    }
  })

  let [state, dispatch] = useReducer(reducer, initState)

  //导航数据
  let [navapp, setNavapp] = useState([
    { id: 1, path: '/home', icon: <HomeO />, title: '首页' },
    { id: 2, path: '/sublist', icon: <Search />, title: '订阅' },
    { id: 3, path: '/my', icon: <FriendsO />, title: '我的' },
  ])
  return (<Ctx.Provider value={{
    ...state,
    dispatch
  }}>
    <div>

      <Suspense fallback={<div>加载中...</div>}>
        <Switch>
          <Route path='/home' component={Home} />
          <Route path='/sublist' component={Sublist} />
          <Route path='/my' component={My} />
          <Route path='/details' component={Details} />
          <Route path='/login' component={Login} />
          <Redirect from='/' to='/home' />
        </Switch>
      </Suspense>



      <div className='demo-tabbar'>
        <Tabbar value={location.pathname} onChange={(path) => {
          //编程式跳转
          history.push(path)
        }} route>
          {
            navapp.map(item => {
              return <Tabbar.Item name={item.path} key={item.id} icon={item.icon}>
                {item.title}
              </Tabbar.Item>
            })
          }

        </Tabbar>
      </div>
    </div>
  </Ctx.Provider>

  )
}

//export default withRouter(App)
export default App